<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{MessageRecord, MessageTemplateConfig, User};
use app\service\MessageService;
use think\facade\{Db, Log};
use think\Request;

class NotificationController extends BaseController
{
    /**
     * 获取消息发送记录
     */
    public function records(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 消息类型筛选
            if (isset($params['message_type'])) {
                $where[] = ['message_type', '=', $params['message_type']];
            }
            
            // 发送状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            // 时间范围筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = MessageRecord::where($where)
                ->with(['user'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取消息发送记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 发送自定义消息
     */
    public function send(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            if (empty($params['template_id']) || empty($params['user_ids'])) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            
            // 获取消息模板
            $template = MessageTemplateConfig::where([
                'id' => $params['template_id'],
                'merchant_id' => $merchant_id,
                'status' => 1
            ])->find();
            
            if (!$template) {
                return json(['code' => 1, 'msg' => '消息模板不存在或已禁用']);
            }
            
            // 获取用户列表
            $users = User::where([
                ['merchant_id', '=', $merchant_id],
                ['id', 'in', $params['user_ids']]
            ])->select();
            
            if ($users->isEmpty()) {
                return json(['code' => 1, 'msg' => '未找到有效用户']);
            }
            
            // 批量发送消息
            $messageService = new MessageService();
            foreach ($users as $user) {
                $messageService->send($template, $user->id, $params['variables'] ?? []);
            }
            
            Db::commit();
            return json(['code' => 0, 'msg' => '发送成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('发送自定义消息失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 重试发送失败的消息
     */
    public function retry(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $record = MessageRecord::where([
                'id' => $params['record_id'],
                'merchant_id' => $merchant_id,
                'status' => 2 // 发送失败
            ])->find();
            
            if (!$record) {
                return json(['code' => 1, 'msg' => '消息记录不存在或状态错误']);
            }
            
            // 重试发送
            $messageService = new MessageService();
            $result = $messageService->retry($record);
            
            Db::commit();
            return json(['code' => 0, 'msg' => $result ? '重试成功' : '重试失败']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('重试发送消息失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取消息发送统计
     */
    public function statistics(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            $start_date = $request->get('start_date', date('Y-m-d'));
            $end_date = $request->get('end_date', date('Y-m-d'));
            
            // 按日期统计发送数据
            $daily_stats = MessageRecord::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    "DATE_FORMAT(create_time, '%Y-%m-%d') as date",
                    'count(*) as total_count',
                    'sum(if(status=1,1,0)) as success_count',
                    'sum(if(status=2,1,0)) as fail_count'
                ])
                ->group('date')
                ->select();
            
            // 按消息类型统计
            $type_stats = MessageRecord::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'message_type',
                    'count(*) as count',
                    'sum(if(status=1,1,0)) as success_count'
                ])
                ->group('message_type')
                ->select();
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => [
                'daily' => $daily_stats,
                'type' => $type_stats
            ]]);
        } catch (\Exception $e) {
            Log::error('获取消息发送统计失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 